package it.unibz.easytravel.blogging;

import java.util.ArrayList;
import java.util.Vector;

import it.unibz.easytravel.R;
import it.unibz.easytravel.db.LocationDbAdapter;
import it.unibz.easytravel.db.PlacemarkDbAdapter;
import it.unibz.easytravel.travel.EditTravel;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;

import com.google.android.maps.MapActivity;

public class TrackMap extends MapActivity {

	private static int travel_id;

	protected MapView mMapView = null;
	EditText mEditTextName;
	LinearLayout mInformation;
	MapController mapController;
	Drawable defaultMarker;
	MotionEvent mEvent = null;
	Button addPlacemarkButton;

	private LocationDbAdapter mLocationDb;
	private MapActivity activity;

	private Vector<GeoPoint> locations = null;
	private Vector<Placemark> placemarks = null;
	private PlacemarkDbAdapter mPlacemarkDb;
	static final int CONSTANT = 1000000;

	private Placemark p;
	private EditText mEditViewName;
	private EditText mEditViewDescription;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tracker_map);
		
		SharedPreferences settings = getSharedPreferences(EditTravel.PREFS_NAME, 0);
		travel_id = settings.getInt(EditTravel.TRAVEL_ID, -1);
		
		
		this.activity = this;

		mMapView = (MapView) findViewById(R.id.map);

		mInformation = (LinearLayout) findViewById(R.id.Information);
		mInformation.setVisibility(LinearLayout.INVISIBLE);


		// get the path
		mLocationDb = new LocationDbAdapter(activity);
		mLocationDb.open();

		Cursor locationCursor = mLocationDb.getLocations(travel_id);

		locations = new Vector<GeoPoint>();
		while (locationCursor.moveToNext()) {
			locations.addElement(new GeoPoint(
					(int)(locationCursor.getFloat(locationCursor.getColumnIndexOrThrow("latitude"))*CONSTANT),
					(int)(locationCursor.getFloat(locationCursor.getColumnIndexOrThrow("longitude"))*CONSTANT))
			);
		}


		//get all the placemarks
		mPlacemarkDb = new PlacemarkDbAdapter(activity);
		mPlacemarkDb.open();

		Cursor placemarkCursor = mPlacemarkDb.getPlacemarks(travel_id);
		placemarks = new Vector<Placemark>();
		while (placemarkCursor.moveToNext()) {
			Placemark p = new Placemark (
					placemarkCursor.getInt(placemarkCursor.getColumnIndexOrThrow("_id")),
					placemarkCursor.getString(placemarkCursor.getColumnIndexOrThrow("name")),
					placemarkCursor.getString(placemarkCursor.getColumnIndexOrThrow("description")),
					placemarkCursor.getString(placemarkCursor.getColumnIndexOrThrow("latitude")),
					placemarkCursor.getString(placemarkCursor.getColumnIndexOrThrow("longitude")),
					placemarkCursor.getString(placemarkCursor.getColumnIndexOrThrow("altitude")),
					placemarkCursor.getString(placemarkCursor.getColumnIndexOrThrow("time")),
					placemarkCursor.getString(placemarkCursor.getColumnIndexOrThrow("picture"))
			);
			placemarks.addElement(p);
			Log.i("MAP", p.id+ " " +p.latitude+" " +p.longitude+" " +p.name+" " +p.description+" ");
		}

		ViewGroup zoom = (ViewGroup) findViewById(R.id.zoom);
		zoom.addView(mMapView.getZoomControls());

		defaultMarker = getResources().getDrawable(R.drawable.bubble);

		defaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(),
				defaultMarker.getIntrinsicHeight());

		repaint();
		mapController.setZoom(7);


		mPlacemarkDb.close();
		mLocationDb.close();

		addPlacemarkButton = (Button) findViewById(R.id.Button_AddPlacemark);
		addPlacemarkButton.setOnClickListener(placemarkButtonListener);		
	}

	private void repaint(){
		mMapView.getOverlays().clear();
		mMapView.getOverlays().add(new MapOverlay(defaultMarker));
		mapController = mMapView.getController();
		if (placemarks.size() > 0) {
			mapController.animateTo(placemarks.lastElement().geoPoint);
		}
	}

	private OnClickListener placemarkButtonListener = new OnClickListener() {
		public void onClick(View v) {
			if (addPlacemarkButton.getText().equals("Y")) {
				addPlacemarkButton.setText("N");
				//mInformation.setVisibility(LinearLayout.INVISIBLE);
				mMapView.setOnTouchListener(new OnTouchListener() {
					// @Override
					public boolean onTouch(View v, MotionEvent event) {
						return false;
					}
				});
				repaint();

			} else {
				addPlacemarkButton.setText("Y");
				
				
				mMapView.setOnTouchListener(new OnTouchListener() {
					// @Override
					public boolean onTouch(View v, MotionEvent event) {
						//remove temporal placemark
						int size = placemarks.size();
						for (int i = 0; i < size; i++) {
							if(placemarks.elementAt(i).temporal){
								placemarks.removeElementAt(i);
								break;
							}
						}

						int x = 0;
						int y = 0;
						// v.dispatchTouchEvent(event);
						mEvent = MotionEvent.obtain(event);
						y = (int) mEvent.getY();
						x = (int) mEvent.getX();
						Projection proj = mMapView.getProjection();
						GeoPoint pontukas = proj.fromPixels(x, y);
						p = new Placemark("","",pontukas, true);
						placemarks.addElement(p);
						
						
						mEditViewName = (EditText) findViewById(R.id.Name);
						mEditViewDescription = (EditText) findViewById(R.id.Description);
						Button mSaveButton = (Button) findViewById(R.id.placemark_Save);
						mSaveButton.setOnClickListener(mSavePlacemark);
						Button mCancelButton = (Button) findViewById(R.id.placemark_Cancel);
						mCancelButton.setOnClickListener(mCancelPlacemark);
						
						repaint();
						mInformation.setVisibility(LinearLayout.VISIBLE);
						return false;
					}
				});
			}
			;
		}
	};

	private class MapOverlay extends ItemizedOverlay<OverlayItem> {
		private ArrayList<OverlayItem> mItemList; 

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {

			super.draw(canvas, mapView, shadow);

			Paint paint = new Paint();
			paint.setARGB(255, 80, 150, 30);
			paint.setStyle(Paint.Style.STROKE);
			paint.setStrokeWidth(3);

			Projection proj = mMapView.getProjection();

			int size = locations.size();

			Vector<Point> points = new Vector<Point>();
			for (int i = 0; i < size; i++) {
				points.addElement(proj.toPixels(locations.elementAt(i), null));
			}

			for (int j = 0; j < size - 1; j++) {
				canvas.drawLine(points.elementAt(j).x, points.elementAt(j).y,
						points.elementAt(j + 1).x, points.elementAt(j + 1).y,
						paint);
			}

			MapOverlay.boundCenterBottom(defaultMarker);

		}

		public MapOverlay(Drawable pMarker) {
			super(pMarker);

			mItemList = new ArrayList<OverlayItem>();
			int size = placemarks.size();
			Placemark p;
			for (int i = 0; i < size; i++) {
				p = placemarks.elementAt(i);
				mItemList.add(new OverlayItem(p.geoPoint, p.name, p.description));
			}
			populate();
		}

		@Override
		protected OverlayItem createItem(int pIndex) {
			return mItemList.get(pIndex);
		}

		protected boolean onTap(int pIndex) {

			if(pIndex<placemarks.size()){
			mEditViewName = (EditText) findViewById(R.id.Name);
			mEditViewDescription = (EditText) findViewById(R.id.Description);

			p = placemarks.elementAt(pIndex);
			
			mEditViewName.setText(p.name);
			mEditViewDescription.setText(p.description);
			
			Button mSaveButton = (Button) findViewById(R.id.placemark_Save);
			mSaveButton.setOnClickListener(mSavePlacemark);
			
			Button mCancelButton = (Button) findViewById(R.id.placemark_Cancel);
			mCancelButton.setOnClickListener(mCancelPlacemark);

			mInformation.setVisibility(LinearLayout.VISIBLE);
		}
			return false;

		}

		@Override
		public int size() {
			return mItemList.size();
		}
	}

	public OnClickListener mSavePlacemark = new OnClickListener() {
		public void onClick(View v) {
			//do the changes in database
			p.name = mEditViewName.getText().toString();
			p.description = mEditViewDescription.getText().toString();
			mPlacemarkDb = new PlacemarkDbAdapter(activity);
			mPlacemarkDb.open();
			if(p.temporal){
				mPlacemarkDb.createPlacemark(travel_id, p.name, p.description, p.geoPoint.getLatitudeE6()/1000000.0+"", p.geoPoint.getLongitudeE6()/1000000.0+"", "0", "", null);
				p.temporal = false;
			}else{
				mPlacemarkDb.updatePlacemarkInfo(p.name,p.description,p.id);	
			}
			mPlacemarkDb.close();
			mInformation.setVisibility(LinearLayout.INVISIBLE);

			repaint();
			Toast.makeText(TrackMap.this, "Saved", Toast.LENGTH_SHORT).show();

		}
	};

	public OnClickListener mCancelPlacemark = new OnClickListener() {
		public void onClick(View v) {
			mInformation.setVisibility(LinearLayout.INVISIBLE);
			int size = placemarks.size();
			for (int i = 0; i < size; i++) {
				if(placemarks.elementAt(i).temporal){
					placemarks.removeElementAt(i);
					break;
				}

			}
			repaint();
			Toast.makeText(TrackMap.this, "Canceled", Toast.LENGTH_SHORT).show();
		}
	};

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

}
